package com.llkj.qingnianguoxue.music;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jm.chat.entity.Event;
import com.jm.chat.entity.EventType;
import com.jm.chat.utils.HandleResponseCode;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.InterestCircleAdapter;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.bean.CircleListBean;
import com.llkj.qingnianguoxue.bean.MyFriendListBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.mine.MyFriendsActivity;
import com.llkj.qingnianguoxue.util.DialogUtil;
import com.llkj.qingnianguoxue.util.DisplayUtil;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.helper.LoadDataHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.options.MessageSendingOptions;
import cn.jpush.im.android.eventbus.EventBus;
import cn.jpush.im.api.BasicCallback;

import static com.llkj.qingnianguoxue.circle.MyChatActivity.APP_KEY;

public class ShareCircleListActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener,
        LoadDataHelper.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener{

    @BindView(R.id.et_search)
    protected EditText etSearchInput;
    @BindView(R.id.refresh_layout)
    protected SwipeRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    protected RecyclerView lvCircleView;//评价
    private InterestCircleAdapter myCircleAdapter;
    private List<CircleListBean.CircleBean> mCircleData;
    private int totalSize,mPage,mCurrentPosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_circle_list);
        ButterKnife.bind(this);

        initData();
        loadWaitDialog();
        onRefresh();
    }

    private void initData(){
        RelativeLayout rlTop = findViewById(R.id.rl_top);
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTop,R.color.gray_bar);

        refreshLayout.setColorSchemeResources(R.color.blue3989ff);
        lvCircleView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        int width = DisplayUtil.dip2px(this,10);
        lvCircleView.setPadding(width,0,width,0);

        mCircleData = new ArrayList<>();
        myCircleAdapter = new InterestCircleAdapter(R.layout.item_interest_circle,mCircleData,null);
        myCircleAdapter.setType(2);
        lvCircleView.setAdapter(myCircleAdapter);
        refreshLayout.setOnRefreshListener(this);
        myCircleAdapter.setOnLoadMoreListener(this);

        lvCircleView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                mCurrentPosition = i;
                final CircleListBean.CircleBean circleBean = mCircleData.get(i);
                Dialog mDialogSureShare = DialogUtil.dialogConfirm(ShareCircleListActivity.this, "确认分享至" + circleBean.getName(), null, "取消", "确认", new DialogUtil.DialogClickListener() {
                    @Override
                    public void dialogClick(int type) {
                        if(type==1){
                            shareEntryCircle(circleBean);
                        }
                    }
                });
                mDialogSureShare.show();
            }
        });
    }

    private void shareEntryCircle(CircleListBean.CircleBean circleBean){
        loadWaitDialog();
        String musicId = getIntent().getStringExtra("musicId");
        String musicName = getIntent().getStringExtra("musicName");
        String singCount = getIntent().getStringExtra("musicSingCount");
        String musicCover = getIntent().getStringExtra("musicCover");
        String musicPath = getIntent().getStringExtra("musicPath");
        //把名片的userName和appKey通过extra发送给对方
        TextContent content = new TextContent("分享作品到圈子");
        content.setStringExtra("businessCard", "businessCard");
        content.setStringExtra("musicId",musicId);
        content.setStringExtra("musicName",musicName);
        content.setStringExtra("musicSingCount",singCount);
        content.setStringExtra("musicCover",musicCover);
        content.setStringExtra("musicPath",musicPath);
        Conversation conversation = JMessageClient.getGroupConversation(Long.parseLong(circleBean.getHx_id()));
        if (conversation == null) {
            conversation = Conversation.createGroupConversation(Long.parseLong(circleBean.getHx_id()));
            EventBus.getDefault().post(new Event.Builder()
                    .setType(EventType.createConversation)
                    .setConversation(conversation)
                    .build());
        }
        Message textMessage = conversation.createSendMessage(content);
        MessageSendingOptions options = new MessageSendingOptions();
        options.setNeedReadReceipt(true);
        JMessageClient.sendMessage(textMessage, options);
        textMessage.setOnSendCompleteCallback(new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                dismissWaitDialog();
                if (i == 0) {
                    Toast.makeText(ShareCircleListActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
                } else {
                    HandleResponseCode.onHandle(ShareCircleListActivity.this, i, false);
                }
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.tv_search})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_search:
                String etWord = etSearchInput.getText().toString();

                break;
        }
    }

    @Override
    public void onLoadMore() {
        mPage++;
        getCircleData();
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        getCircleData();
    }

    @Override
    public void onLoadMoreRequested() {
        LoadDataHelper.loadMoreRequest(this, myCircleAdapter, null, lvCircleView, totalSize);
    }

    /**
     * 获取圈子数据
     */
    private void getCircleData(){
        HttpMethod.circleIndex(this, this, "2", String.valueOf(mPage));
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if(method == HttpMethod.HTTP_CIRCLE_INDEX1){
            CircleListBean circleListBean = GsonUtil.GsonToListBean(data, CircleListBean.class);
            if(circleListBean != null){
                try {
                    totalSize = Integer.parseInt(circleListBean.getNum());
                }catch (Exception e){}

                if (mPage == 1) {
                    mCircleData.clear();
                    LoadDataHelper.refreshComplete(myCircleAdapter, mCircleData, refreshLayout, lvCircleView);
                } else {
                    myCircleAdapter.setEnableLoadMore(true);
                    myCircleAdapter.loadMoreComplete();
                }
                mCircleData.addAll(circleListBean.getMy_circle());
                mCircleData.addAll(circleListBean.getAdd_circle());
                myCircleAdapter.notifyDataSetChanged();
            }
        }
    }
}
